//
//  main.c
//  C_7数据结构和动态存储
//
//  Created by Robin on 16/3/17.
//  Copyright © 2016年 cnbm. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 链表 递归结构
typedef struct island{
    char *name;
    char *opens;
    char *closes;
    struct island *next;
}island;

// 二叉树
typedef struct node{
    char *question;
    struct node *yes;
    struct node *no;
}node;

node *create (char *question);
int yes_no (char *question);
void release_node (node *n);

void display_island (island *start);// 遍历链表
island* create_island();                // 动态分配内存

int main(int argc, const char * argv[]) {

    char question[80];
    char suspect[20];
    
    node *start = create("Does suspect has a mustache");
    
    start->yes = create("奥巴马");
    start->no = create("安倍");
    
    node *current;
    
    do {
        current = start;
        while (1) {
            
            if (yes_no(current->question)) {
                
                if (current->yes) {
                    current = current->yes;
                }else{
                    printf("SUSPECT IDENTIFIED\n");
                    break;
                }
                
            }else if (current->no){
                current = current->no;
            }else{
                /* Make the yes_node to new suspect*/
                printf("Who's the suspect?");
                fgets(suspect, 20, stdin);
                node *yes_node = create(suspect);
                current->yes = yes_node;
                
                node *no_node = create(current->question);
                current->no = no_node;
                
                /*Then replace this question with a new question*/
                printf("Give me a question that is TURE for %s but not for %s?",suspect,current->question);
                fgets(question, 80, stdin);
                free(current->question);
                
                current->question = strdup(question);
                break;
            }
        }
    }
    while (yes_no("Run again"));
    
    release_node(start);
    return 0;
}

node *create (char *question){
    node *n = malloc(sizeof(node));
    n->question = strdup(question);
    n->yes = NULL;
    n->no = NULL;
    
    return n;
}

int yes_no (char *question){
    char answer[3];
    printf("%s?(y/n)",question);
    //scanf("%s",answer);
    fgets(answer, 3, stdin);
    return answer[0] == 'y';
}

void release_node (node *n){
    if (n) {
        if (n->yes) {
            release_node(n->yes);
        }
        if (n->no) {
            release_node(n->no);
        }
        if (n->question) {
            free(n->question);
        }
        free(n);
    }
}

